package com.extsci.webmail.web.service;

import com.extsci.webmail.common.entity.communicate.CommunicateGroup;
import com.extsci.webmail.common.entity.communicate.CommunicateUser;
import com.extsci.webmail.common.entity.http.ObjectRestResponse;
import com.extsci.webmail.common.entity.http.ResponseStatus;
import com.extsci.webmail.common.util.CommonUtils;
import com.extsci.webmail.mapper.CommunicateMapper;
import com.yanchang.common.context.BaseContextHandler;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 通讯录服务
 * @author ccoke
 */
@Service
public class CommunicateService{

    private final CommunicateMapper communicateMapper;

    @Value("${webmail.nogroup}")
    private String noGroup;

    @Autowired
    public CommunicateService(CommunicateMapper communicateMapper) {
        this.communicateMapper = communicateMapper;
    }


    /**
     * 获取整个通讯录
     */
    public List<CommunicateGroup> getAll() {
        List<CommunicateGroup> groups = communicateMapper.selectAllByUsername(BaseContextHandler.getUsername());
        return groups == null ? new ArrayList<>() : groups;
    }

    /**
     * 获取通讯录分组列表
     */
    public List<CommunicateGroup> getGroups() {
        List<CommunicateGroup> groups = communicateMapper.selectGroupsByUsername(BaseContextHandler.getUsername());
        return groups == null ? new ArrayList<>() : groups;
    }

    /**
     * 通过分组Uuid获取联系人列表
     */
    public List<CommunicateUser> getUsers(String groupUuid) {
        return isGroupBelongToUser(groupUuid) ? communicateMapper.selectUsersByGroupUuid(groupUuid) : new ArrayList<>();
    }

    /**
     * 创建分组
     */
    public ObjectRestResponse<List<CommunicateGroup>> addGroup(String groupName) {
        // 不可以手动创建未分组分组
        if (noGroup.equals(groupName.trim())){
            return new ObjectRestResponse<>(ResponseStatus.CANNOT_CREATE_NO_GROUP);
        }
        CommunicateGroup group = new CommunicateGroup()
                .setUuid(CommonUtils.createUUID())
                .setName(groupName)
                .setUsername(BaseContextHandler.getUsername())
                .setCreateAt(new Date());
        communicateMapper.insertGroup(group);
        return new ObjectRestResponse<>(ResponseStatus.SUCCESS, getGroups());
    }

    /**
     * 根据分组Uuid添加联系人
     */
    public ObjectRestResponse<List<CommunicateUser>> addUsers(String groupUuid, List<CommunicateUser> users) {
        if (!isGroupBelongToUser(groupUuid)) {
            return new ObjectRestResponse<>(ResponseStatus.CANNOT_ADD_USERS_TO_GROUP);
        }
        // 参数校验
        for (CommunicateUser user: users) {
            if (StringUtils.isBlank(user.getName()) || StringUtils.isBlank(user.getEmail())){
                return new ObjectRestResponse<>(ResponseStatus.PARAM_ERROR);
            }
        }
        Date now = new Date();
        for (CommunicateUser user: users) {
            user.setUuid(CommonUtils.createUUID()).setGroupUuid(groupUuid).setCreateAt(now);
            communicateMapper.insertUser(user);
        }
        List<CommunicateUser> userList = communicateMapper.selectUsersByGroupUuid(groupUuid);
        return new ObjectRestResponse<>(ResponseStatus.SUCCESS, userList == null ? new ArrayList<>() : userList);
    }

    /**
     * 修改分组名
     */
    public ObjectRestResponse<List<CommunicateGroup>> modifyGroup(String groupUuid, String name) {
        if (!isGroupBelongToUser(groupUuid)) {
            return new ObjectRestResponse<>(ResponseStatus.CANNOT_MODIFY_GROUP);
        }
        if (noGroup.equals(name.trim())){
            return new ObjectRestResponse<>(ResponseStatus.CANNOT_CREATE_NO_GROUP);
        }
        communicateMapper.updateGroupName(BaseContextHandler.getUsername(), groupUuid, name);
        return new ObjectRestResponse<>(ResponseStatus.SUCCESS, getGroups());
    }

    /**
     * 修改联系人信息
     */
    public ObjectRestResponse<List<CommunicateUser>> modifyUser(String groupUuid, CommunicateUser user) {
        if (!isGroupBelongToUser(groupUuid)) {
            return new ObjectRestResponse<>(ResponseStatus.CANNOT_MODIFY_GROUP);
        }
        communicateMapper.updateUser(groupUuid, user);
        return new ObjectRestResponse<>(ResponseStatus.SUCCESS, communicateMapper.selectUsersByGroupUuid(groupUuid));
    }

    /**
     * 删除分组
     */
    public ObjectRestResponse<List<CommunicateGroup>> removeGroup(String groupUuid) {
        if (!isGroupBelongToUser(groupUuid)) {
            return new ObjectRestResponse<>(ResponseStatus.CANNOT_MODIFY_GROUP);
        }
        String username = BaseContextHandler.getUsername();
        // 判断未分组人员分组是否存在,没有则创建，有则插入

        String noGroupUuid = communicateMapper.selectGroupUuidByNameAndUserName(username, noGroup);
        // 如果要删除的分组ID与未分组ID相同，则不允许
        if (noGroupUuid != null && groupUuid.equals(noGroupUuid)){
            return new ObjectRestResponse<>(ResponseStatus.CANNOT_DELETE_NO_GROUP);
        }
        // 不存在"未分组联系人"则创建
        if (noGroupUuid == null) {
            noGroupUuid = CommonUtils.createUUID();
            communicateMapper.insertGroup(new CommunicateGroup()
                    .setUuid(noGroupUuid).setName(noGroup).setUsername(username).setCreateAt(new Date()));
        }
        // 将原分组下的所有联系人修改到未分组下
        communicateMapper.updateUsersGroup(groupUuid, noGroupUuid);
        // 删除原分组
        communicateMapper.deleteGroup(username, groupUuid);
        return new ObjectRestResponse<>(ResponseStatus.SUCCESS, getGroups());
    }

    /**
     * 删除联系人(多选)
     */
    public void removeUsers(String groupUuid, List<String> users) {
        if (!isGroupBelongToUser(groupUuid)) {
            return;
        }
        for (String user : users) {
            communicateMapper.deleteUser(user, groupUuid);
        }
    }

    /**
     * 将联系人移动分组(多选)
     */
    public ObjectRestResponse<List<CommunicateGroup>> moveUsers(String groupUuid, String newGroupUuid, List<String> users) {
        // 判断分组是否存在
        if (!isGroupBelongToUser(groupUuid) || !isGroupBelongToUser(newGroupUuid)) {
            return new ObjectRestResponse<>(ResponseStatus.NOTFOUNT);
        }
        for (String user: users) {
            communicateMapper.updateUserGroup(user, groupUuid, newGroupUuid);
        }
        return new ObjectRestResponse<>(ResponseStatus.SUCCESS, getGroups());
    }


    /**
     * 判断分组是否属于用户
     */
    private boolean isGroupBelongToUser(String uuid) {
        String username = BaseContextHandler.getUsername();
        CommunicateGroup communicateGroup = communicateMapper.selectGroupByUuid(uuid);
        return communicateGroup != null && username.equals(communicateGroup.getUsername());
    }

}
